package controllers;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.google.gson.Gson;

import play.db.DB;
import play.mvc.Controller;
import models.*;

public class Security extends Controller{
	
	static Gson gson = new Gson();
	
	public static void authenticate(String username, String password) {
    	Usuario user = null;
    	Connection conn = DB.getConnection();
        try {
        	ResultSet rs = conn.createStatement().executeQuery("select * from SIGPC_USUARIO where USUUSUARIO = '" + username + "' and USUCONTRASENIA = '"+ password +"'");
    		while (rs.next()) {
    			user = new Usuario();
    			user.setId(rs.getInt("USUID"));
    			user.setRolId(rs.getInt("ROLID"));
    			user.setNombre(rs.getString("USUNOMBRE"));
    			user.setEmail(rs.getString("USUEMAIL"));
    			user.setUsuario(rs.getString("USUUSUARIO"));     
			}
        	if( user != null ){
        		session.put("usuario", gson.toJson(user));
        		//System.out.println(user);
    			renderJSON("{\"success\":" + true + "}");
        	}
        	else
        		renderJSON("{\"success\":" + false + "}");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderJSON("{\"success\":" + false + "}");
		}
    }
    /**
     * render current user
     */
    public static void currentUser() {    	
		Usuario userInfo = new Usuario();		
		userInfo = gson.fromJson(session.get("usuario"), Usuario.class);
		renderJSON(userInfo);
	}
    
    /**
     * logOut
     */
	public static void logOut() {
		session.put("usuario", null);
		redirect("/login");
	}
	
	/**
	 * Checks if is authenticated.
	 * 
	 * @return true, if is authenticated
	 */
	public static boolean isAuthenticated() {
		String userJSON = session.get("usuario");
		Usuario user = gson.fromJson(userJSON, Usuario.class);
		if (user == null) {
			return false;
		} else {
			return true;
		}
	}
	
	public static boolean havePermission(){
		Rol userRol = null;
		String userJSON = session.get("usuario");
		Usuario user = gson.fromJson(userJSON, Usuario.class);
    	Connection conn = DB.getConnection();
        try {
        	ResultSet rs = conn.createStatement().executeQuery("select * from SIGPC_ROL where ROLID = '" + user.getRolId() + "'");
    		while (rs.next()) {
    			userRol = new Rol();
    			userRol.setId(rs.getInt("ROLID"));
    			userRol.setNombre(rs.getString("ROLNOMBRE"));
    		}
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(userRol != null && (userRol.getId()== 1 ||userRol.getId()== 2) ){					
			return true;
		}
		else			
			return false;
	}

}
